from typing import Dict, List, Optional, Any
from enum import Enum
from pydantic import BaseModel, Field
import time


class KnowledgeBaseType(Enum):
    DOCUMENT = "document"
    DATABASE = "database"
    API = "api"
    CUSTOM = "custom"


class ReplyStrategy(Enum):
    SINGLE = "single"  # 单条回复
    MULTIPART = "multipart"  # 分段回复
    QUEUED = "queued"  # 队列回复


class AIAgentConfig(BaseModel):
    """AI智能体基础配置"""

    # 基础配置
    agent_name: str = Field(..., description="智能体名称")
    agent_model: str = Field(..., description="智能体模型")
    introduction: str = Field(..., description="相关介绍")
    prompt_role: str = Field(..., description="提示词角色")
    background: str = Field(..., description="背景")
    responsibilities: List[str] = Field(..., description="职责")
    workflow: List[str] = Field(..., description="工作流程")
    communication_style: str = Field(..., description="沟通方式")
    purpose: str = Field(..., description="目的")

    # 知识库配置
    knowledge_base_type: KnowledgeBaseType = Field(..., description="知识库类型")
    attached_knowledge_base: str = Field(..., description="挂靠知识库")
    citation_limit: int = Field(default=5, description="引用上限")

    # 拟人化配置
    context_window: int = Field(default=10, description="上下文数")
    vocabulary_diversity: float = Field(default=0.8, ge=0.0, le=1.0, description="词汇多样性")
    result_similarity: float = Field(default=0.3, ge=0.0, le=1.0, description="结果相似性")

    # 固定话术配置
    fixed_responses: Dict[str, str] = Field(default_factory=dict, description="关键词->固定回复映射")

    # 调用设置
    multi_message_strategy: ReplyStrategy = Field(..., description="多条信息回复策略")
    image_reply_enabled: bool = Field(default=True, description="接收到图片进行固定回复")
    image_fixed_response: Optional[str] = Field(default="我主要处理文本信息，暂时无法分析图片内容。", description="图片固定回复")
    stop_keywords: List[str] = Field(default_factory=list, description="触发停止回复的关键词")
    multipart_reply: bool = Field(default=False, description="分段回复")
    takeover_time: int = Field(default=30, description="接管时间(秒)")


class AIAgent:
    def __init__(self, config: AIAgentConfig):
        self.config = config
        self.conversation_history = []
        self.last_interaction_time = time.time()

    def process_message(self, user_input: str, has_image: bool = False) -> Optional[str]:
        """处理用户输入并返回回复"""

        # 检查是否需要停止回复
        if self._should_stop_reply(user_input):
            return None

        # 处理图片消息
        if has_image and self.config.image_reply_enabled:
            return self.config.image_fixed_response

        # 检查固定话术
        fixed_response = self._check_fixed_responses(user_input)
        if fixed_response:
            return fixed_response

        # 更新交互时间
        self.last_interaction_time = time.time()

        # 添加到对话历史
        self._update_conversation_history(user_input)

        # 生成AI回复（这里需要接入实际的AI模型）
        ai_response = self._generate_ai_response(user_input)

        return ai_response

    def _should_stop_reply(self, user_input: str) -> bool:
        """检查是否应该停止回复"""
        return any(keyword in user_input.lower() for keyword in self.config.stop_keywords)

    def _check_fixed_responses(self, user_input: str) -> Optional[str]:
        """检查固定话术"""
        user_input_lower = user_input.lower()
        for keyword, response in self.config.fixed_responses.items():
            if keyword.lower() in user_input_lower:
                return response
        return None

    def _update_conversation_history(self, user_input: str):
        """更新对话历史"""
        self.conversation_history.append({"role": "user", "content": user_input})
        # 保持上下文窗口大小
        if len(self.conversation_history) > self.config.context_window * 2:
            self.conversation_history = self.conversation_history[-(self.config.context_window * 2):]

    def _generate_ai_response(self, user_input: str) -> str:
        """生成AI回复（需要接入实际AI模型）"""
        # 这里应该是调用AI模型的逻辑
        # 暂时返回一个示例回复
        return f"基于我的角色'{self.config.prompt_role}'，我对您的问题的回复是：这是一个示例回复。"

    def is_takeover_active(self) -> bool:
        """检查接管时间是否有效"""
        return (time.time() - self.last_interaction_time) <= self.config.takeover_time

    def get_agent_info(self) -> Dict[str, Any]:
        """获取智能体信息"""
        return {
            "agent_name": self.config.agent_name,
            "model": self.config.agent_model,
            "introduction": self.config.introduction,
            "purpose": self.config.purpose,
            "status": "active" if self.is_takeover_active() else "inactive"
        }


# 配置示例
def create_customer_service_agent() -> AIAgent:
    """创建客服智能体配置示例"""
    config = AIAgentConfig(
        # 基础配置
        agent_name="智能客服助手",
        agent_model="gpt-4",
        introduction="专业的客户服务AI助手，提供7x24小时在线支持",
        prompt_role="专业客服代表",
        background="经过专业客服培训的AI助手",
        responsibilities=[
            "解答客户咨询",
            "处理客户投诉",
            "提供产品信息",
            "记录客户反馈"
        ],
        workflow=[
            "接收用户问题",
            "分析问题类型",
            "检索相关知识",
            "生成专业回复",
            "记录交互日志"
        ],
        communication_style="友好、专业、耐心",
        purpose="提升客户满意度和服务效率",

        # 知识库配置
        knowledge_base_type=KnowledgeBaseType.DOCUMENT,
        attached_knowledge_base="产品知识库",
        citation_limit=3,

        # 拟人化配置
        context_window=15,
        vocabulary_diversity=0.7,
        result_similarity=0.2,

        # 固定话术
        fixed_responses={
            "你好": "您好！我是智能客服助手，很高兴为您服务！",
            "谢谢": "不客气！很高兴能帮助您！",
            "再见": "感谢您的咨询，再见！祝您生活愉快！"
        },

        # 调用设置
        multi_message_strategy=ReplyStrategy.QUEUED,
        image_reply_enabled=True,
        stop_keywords=["停止", "结束", "退出", "不需要了"],
        multipart_reply=True,
        takeover_time=45
    )

    return AIAgent(config)


# 使用示例
if __name__ == "__main__":
    agent = create_customer_service_agent()

    # 测试消息处理
    test_messages = [
        "你好",
        "我想咨询产品信息",
        "发送图片",
        "谢谢你的帮助",
        "停止服务"
    ]

    for msg in test_messages:
        response = agent.process_message(msg, has_image=("图片" in msg))
        if response:
            print(f"用户: {msg}")
            print(f"AI: {response}")
            print("-" * 50)